package com.tca.common.learning.oss.minio.test.controller;

import com.amazonaws.services.s3.model.Bucket;
import com.tca.common.core.bean.Result;
import com.tca.common.learning.oss.minio.bean.OssTemplate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * @author zhoua
 * @date 2022/11/25 11:48
 */
@RestController
@Slf4j
@RequestMapping("/oss/bucket")
public class BucketController {

    @Autowired
    private OssTemplate ossTemplate;

    /**
     * 创建 bucket
     * @param bucketName
     * @return
     */
    @PutMapping("/{bucketName}")
    public Result createBucket(@PathVariable String bucketName) {
        Optional<Bucket> bucket = ossTemplate.getBucket(bucketName);
        if (bucket.isPresent()) {
            log.info("{} is already exists", bucketName);
            return Result.success();
        }
        ossTemplate.createBucket(bucketName);
        return Result.success();
    }

    /**
     * 获取 bucket
     * @param bucketName
     * @return
     */
    @GetMapping("/{bucketName}")
    public Result<Bucket> getBucket(@PathVariable String bucketName) {
        Optional<Bucket> bucket = ossTemplate.getBucket(bucketName);
        if (!bucket.isPresent()) {
            return Result.failure(bucketName + " does not exists");
        }
        return Result.success(bucket.get());
    }

    /**
     * 获取所有 buckets
     * @return
     */
    @GetMapping("/list")
    public Result<List<Bucket>> listBuckets() {
        return Result.success(ossTemplate.getAllBuckets());
    }

    /**
     * 获取bucket详情
     * @param bucketName
     * @return
     */
    @GetMapping("/detail/{bucketName}")
    public Result<Map<String, Object>> getBucketDetail(@PathVariable String bucketName) {
        Optional<Bucket> bucket = ossTemplate.getBucket(bucketName);
        if (!bucket.isPresent()) {
            return Result.failure(bucketName + " does not exists");
        }
        Map<String, Object> bucketInfo = ossTemplate.getBucketInfo(bucketName);
        return Result.success(bucketInfo);
    }

    /**
     * 删除 bucket
     * @param bucketName
     * @return
     */
    @DeleteMapping("/{bucketName}")
    public Result deleteBucket(@PathVariable String bucketName) {
        Optional<Bucket> bucket = ossTemplate.getBucket(bucketName);
        if (!bucket.isPresent()) {
            return Result.failure(bucketName + " does not exists");
        }
        ossTemplate.removeBucket(bucketName);
        return Result.success();
    }
}
